package model.mediators;

import java.util.Iterator;

import model.item.Inventory;
import model.item.InventoryItem;

/**
 * This mediator is used for exchanging items between an entity and a shopkeeper with no monetary value taken into account.
 * @author Ozzy
 *
 */
public class ExchangeMediator extends InteractionMenuMediator {

	private Inventory active;
	private Inventory passive;
	private int favor;
	private InteractiveMediator parentMediator;
	private WindowedItemInteraction window;
	
	public ExchangeMediator(Inventory active, Inventory passive, int favor, InteractiveMediator parentMediator) {
		this.active = active;
		this.passive = passive;
		this.favor = favor;
		this.parentMediator = parentMediator;
		init();
	}
	
	public void init() {
		
		if (favor >= 25) {
		window = new WindowedItemInteraction("Item Exchange", this);
		Iterator<InventoryItem> activeIterator = active.getInventory();
		Iterator<InventoryItem> passiveIterator = passive.getInventory();
		while (activeIterator.hasNext()) {
			InventoryItem nextItem = activeIterator.next();
			window.addOptionLeft(new ItemInteractionOption(nextItem.getName(), nextItem) {
				public void actionPerformed() {
					giveItem(getItem());
					window.removeInteractionOption(this);
					window.refresh();
				}
			}); 
		}
		while (passiveIterator.hasNext()) {
			InventoryItem nextItem = passiveIterator.next();
			window.addOptionRight(new ItemInteractionOption(nextItem.getName(), nextItem) {
				public void actionPerformed() {
					receiveItem(getItem());
					window.removeInteractionOption(this);
					window.refresh();
				}
			}); 
		}
		
		
		window.createWindow();
		}
		
		else {
			WindowedInteraction failWindow = new WindowedInteraction("Not Enough Favorability", this);
			failWindow.createWindow();
		}
	}
	public void exit() {
		parentMediator.show();
	}
	
	/**
	 * Give an item to another entity.
	 * @param item
	 */
	private void giveItem(InventoryItem item) {
		transact(item, active, passive);
	}
	
	/**
	 * Take an item from another entity.
	 * @param item
	 */
	private void receiveItem(InventoryItem item) {
		transact(item, passive, active);
	}
	
	private void transact(InventoryItem item, Inventory giver, Inventory receiver) {
		if (receiver.canReceive(item)) {
			giver.removeItem(item);
			receiver.addItem(item);
		}
		
		else {
			return;
		}
	}
}
	
